package game

import (
	"fmt"
	"math"
	"math/rand"
	"server/GoUtil"
	"server/MergeConst"
	"server/db"
	"server/gamedata"
	"server/msg"
	"sort"
	"strconv"
	"strings"
	"time"

	"github.com/robfig/cron/v3"

	"google.golang.org/protobuf/proto"
)

type ChampshipsGroupData struct {
	MChampshipPlayerScoreList []*msg.ChampshipsPlayerInfo
	GroupId                   int32
	CurChampshipId            int32
	ActiveGroup               int32
}

type NewChampshipsManager struct {
	MStatus              int32
	MChampshipMap        map[int32]*db.SqlChampionshipsStruct
	MChampshipPlayerMap  map[int32][]*msg.ChampshipsPlayerInfo
	IsSettle             int32
	IsLoadDB             bool
	MUpdateNotifyList    []int32
	McronSave            *cron.Cron
	McronSaveID          cron.EntryID
	RobotCronID          cron.EntryID
	RobotCronID10s       cron.EntryID
	RobotCronID5m        cron.EntryID
	MPlayerBaseInfoMap   map[int32]*db.ResPlayerBaseInfo
	MWaitToRankList      map[int32]*db.SqlPlayerChampionData
	MAllPlayerRankList   map[int32]*db.SqlPlayerChampionData
	MChampshipsGroupData map[int32]*ChampshipsGroupData
}

func (p *NewChampshipsManager) SaveDataFromDB(Key interface{}) bool {

	return true
}

func (p *NewChampshipsManager) DeleteOutLineChampship(CurChampshipsId int32) {
	sqlStr := "DELETE FROM t_championships_data WHERE CurChampshipsId = ?"

	for k, v := range p.MChampshipsGroupData {
		if v.CurChampshipId == CurChampshipsId {
			delete(p.MChampshipsGroupData, k)
		}
	}
	result, err := db.SqlDb.Exec(sqlStr, CurChampshipsId)
	if err != nil {
		fmt.Printf("exec failed, err:%v\n", err)
		return
	}
	affectedRows, err := result.RowsAffected()
	if err != nil {
		fmt.Printf("get affected failed, err:%v\n", err)
		return
	} else {
		fmt.Printf("delete t_championships_data affectedRows:%d\n", affectedRows)
	}
}

func (p *NewChampshipsManager) DeleteUneffectPlayer(deleteIds []int32) {
	sqlStr := "DELETE FROM t_player_baseinfo WHERE dwUin = ?"

	for i := 0; i < len(deleteIds); i++ {
		_, err := db.SqlDb.Exec(sqlStr, deleteIds[i])
		if err != nil {
			fmt.Printf("exec failed, err:%v\n", err)
		}

	}
}

func (p *NewChampshipsManager) GetFriendListId(id int32) []int32 {

	sqlStr := "SELECT * FROM t_player_Friend_Data WHERE dwUin = ?"
	sqlStruck := db.SqlFriendStruct{}
	ret := []int32{}

	if err := db.SqlDb.Get(&sqlStruck, sqlStr, id); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)

	} else {
		if sqlStruck.FriendList != "" {
			arr := strings.Split(sqlStruck.FriendList, "_")
			for i := 0; i < len(arr); i++ {
				id, _ := strconv.ParseInt(arr[i], 10, 32)
				ret = append(ret, int32(id))
			}
		}
	}
	return ret
}

func (p *NewChampshipsManager) ReqPlayerChampshipData(player *Player, buf []byte) {
	req := &msg.ReqPlayerChampshipData{}
	proto.Unmarshal(buf, req)
	res := &msg.ResPlayerChampshipData{}

	res.Status = p.MStatus
	res.IsSettle = p.IsSettle
	res.CurChampshipsId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId
	if res.Status > 0 {
		p.EnterWaitRankList(player.M_DwUin, 0)
		rankInfo := p.MAllPlayerRankList[player.M_DwUin]
		res.IsEnterRank = rankInfo.IsEnterRank
		res.CurScore = rankInfo.CurScore
		res.CurMaxScore = rankInfo.CurMaxScore
		res.CurRank = rankInfo.CurRank
		res.TodayOpenTime = rankInfo.TodayOpenTime
		res.EndTime = G_GameLogicPtr.M_SvrGlobal.StartChampshipsSvrTime + MergeConst.G_Champion_Duration
		res.EndSettleTime = G_GameLogicPtr.M_SvrGlobal.StartChampshipsSvrTime - MergeConst.G_Champion_Start_Offset + MergeConst.G_Champion_settlement_Duration
		res.ChampshipsGroupID = rankInfo.ChampshipsGroupID
		res.LastChampGroupID = rankInfo.LastChampGroupID
	} else {
		sqlStr := "SELECT * FROM t_Player_championships_data WHERE dwUin = ?"
		rankInfo := &db.SqlPlayerChampionData{}
		rankInfo.DwUin = player.M_DwUin
		if err := db.SqlDb.Get(rankInfo, sqlStr, player.M_DwUin); err != nil {

		} else {

		}
		res.ChampshipsGroupID = rankInfo.ChampshipsGroupID
		res.LastChampGroupID = rankInfo.ChampshipsGroupID
	}

	agent := player.GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResPlayerChampshipData", data)
}

func (p *NewChampshipsManager) EnterWaitRankList(dwUin int32, Score int32) bool {
	sqlStr := "SELECT * FROM t_Player_championships_data WHERE dwUin = ?"
	sqlStruck := &db.SqlPlayerChampionData{}
	sqlStruck.DwUin = dwUin
	rankInfo, ok := p.MAllPlayerRankList[dwUin]

	timeStamp := time.Now().Unix()
	t := time.Unix(timeStamp, 0).Local()
	zero := timeStamp - (int64)(t.Hour()*3600+t.Minute()*60+t.Second())
	OpenTime := zero + MergeConst.G_Champion_Start_Offset

	if ok {
		LastScore := rankInfo.CurScore
		IsEnterRank := rankInfo.IsEnterRank
		if rankInfo.TodayOpenTime == int32(OpenTime) {
			rankInfo.CurScore = rankInfo.CurScore + Score

		} else { //第二天开始
			rankInfo.TodayOpenTime = int32(OpenTime)
			rankInfo.CurScore = Score
			rankInfo.IsEnterRank = 0
			rankInfo.LastChampGroupID = rankInfo.ChampshipsGroupID
			if IsEnterRank == 1 {
				newStr := fmt.Sprintf("%d,%d,%d", rankInfo.CurRank, LastScore, rankInfo.CurMaxScore)
				if rankInfo.HistoryData != "" {
					units := strings.Split(rankInfo.HistoryData, ";")
					temp := []string{}

					if len(units) >= 3 {

						for i := 1; i < len(units); i++ {
							temp = append(temp, units[i])
						}
						temp = append(temp, newStr)
						rankInfo.HistoryData = strings.Join(temp, ";")
					} else {
						temp = append(temp, rankInfo.HistoryData)
						temp = append(temp, newStr)
						rankInfo.HistoryData = strings.Join(temp, ";")
					}
				} else {
					rankInfo.HistoryData = newStr
				}

			}
			rankInfo.CurMaxScore = MergeConst.G_Champion_Max_Score

		}

		if rankInfo.CurScore >= MergeConst.G_Champion_Unlock_Score && rankInfo.IsEnterRank == 0 {
			p.MWaitToRankList[dwUin] = rankInfo
		}
		if rankInfo.CurScore >= rankInfo.MaxHistoryScore {
			rankInfo.MaxHistoryScore = rankInfo.CurScore
		}
		db.FormatAllMemUpdateDb(rankInfo, "t_Player_championships_data", "dwUin")
		return rankInfo.IsEnterRank == 1

	} else {
		IsUpdate := false
		if err := db.SqlDb.Get(sqlStruck, sqlStr, dwUin); err != nil {
			IsUpdate = false

		} else {
			IsUpdate = true
		}
		LastScore := sqlStruck.CurScore
		IsEnterRank := sqlStruck.IsEnterRank

		if sqlStruck.TodayOpenTime == int32(OpenTime) {
			sqlStruck.CurScore = sqlStruck.CurScore + Score

		} else {
			sqlStruck.TodayOpenTime = int32(OpenTime)
			sqlStruck.CurScore = Score
			sqlStruck.IsEnterRank = 0
			sqlStruck.LastChampGroupID = sqlStruck.ChampshipsGroupID
			if IsEnterRank == 1 {
				newStr := fmt.Sprintf("%d,%d,%d", sqlStruck.CurRank, LastScore, sqlStruck.CurMaxScore)
				if sqlStruck.HistoryData != "" {
					units := strings.Split(sqlStruck.HistoryData, ";")
					temp := []string{}

					if len(units) >= 3 {

						for i := 1; i < len(units); i++ {
							temp = append(temp, units[i])
						}
						temp = append(temp, newStr)
						sqlStruck.HistoryData = strings.Join(temp, ";")
					} else {
						temp = append(temp, sqlStruck.HistoryData)
						temp = append(temp, newStr)
						sqlStruck.HistoryData = strings.Join(temp, ";")
					}
				} else {
					sqlStruck.HistoryData = newStr
				}

			}

			sqlStruck.CurMaxScore = MergeConst.G_Champion_Max_Score
		}
		p.MAllPlayerRankList[dwUin] = sqlStruck

		if sqlStruck.CurScore >= MergeConst.G_Champion_Unlock_Score && sqlStruck.IsEnterRank == 0 {
			p.MWaitToRankList[dwUin] = sqlStruck
		}
		if sqlStruck.CurScore >= sqlStruck.MaxHistoryScore {
			sqlStruck.MaxHistoryScore = sqlStruck.CurScore
		}
		if IsUpdate {
			db.FormatAllMemUpdateDb(sqlStruck, "t_Player_championships_data", "dwUin")
		} else {
			db.FormatAllMemInsertDb(sqlStruck, "t_Player_championships_data")
		}
		return sqlStruck.IsEnterRank == 1
	}

}

func (p *NewChampshipsManager) ScoreGroup(LastScore int32, HistoryScore int32) int {
	ChampshipScoreReward := gamedata.GetConfigByName("ChampshipScoreReward")
	var LastScoreId int = 0
	var HistoryScoreId int = 0
	lenCnt := ChampshipScoreReward.NumRecord()
	for i := 0; i < lenCnt; i++ {
		record := ChampshipScoreReward.Record(i).(*gamedata.ChampshipScoreReward)
		if i < lenCnt-1 {
			recordNext := ChampshipScoreReward.Record(i + 1).(*gamedata.ChampshipScoreReward)
			if int(LastScore) >= record.ScoreNeed && int(LastScore) < recordNext.ScoreNeed {
				LastScoreId = record.Id
			}
			if int(HistoryScore) >= record.ScoreNeed && int(HistoryScore) < recordNext.ScoreNeed {
				HistoryScoreId = record.Id
			}
		}
	}
	record := ChampshipScoreReward.Record(lenCnt - 1).(*gamedata.ChampshipScoreReward)
	if int(LastScore) >= record.ScoreNeed {
		LastScoreId = record.Id
	}
	if int(HistoryScore) >= record.ScoreNeed {
		HistoryScoreId = record.Id
	}
	rate := []int{3, 6, 10, 13, 16, 19, 22, 26, 29}
	var n int = 0
	var h int = 0

	for i := 0; i < len(rate); i++ {
		if LastScoreId <= rate[i] && n == 0 {
			n = i + 1
		}
		if HistoryScoreId <= rate[i] && h == 0 {
			h = i + 1
		}
	}
	if n == 0 {
		n = len(rate) + 1
	}
	if h == 0 {
		h = len(rate) + 1
	}
	if n >= h {
		return n
	} else {
		max := math.Max(float64(n-1), float64(h-2))
		ret := math.Max(max, 1)
		return int(ret)
	}

}

func (p *NewChampshipsManager) InitAIAddScore(Ai int32, energy int32) int32 {
	var addScore int32 = 0
	ran := rand.Intn(2) + 1
	if Ai == 1 {
		Score := float64(energy) / 10.0 * float64(1.0/30)
		if ran == 1 {
			addScore = int32(math.Ceil(Score))
		} else {
			addScore = int32(math.Floor(Score))
		}
	} else if Ai == 2 {
		Score := float64(energy) / 10.0 * 0.667 * float64(1.0/60)
		if ran == 1 {
			addScore = int32(math.Ceil(Score))
		} else {
			addScore = int32(math.Floor(Score))
		}
	} else if Ai == 3 {
		timeStamp := time.Now().Unix()
		t := time.Unix(timeStamp, 0).Local()
		zero := timeStamp - (int64)(t.Hour()*3600+t.Minute()*60+t.Second()) + 3600*24

		Score := float64(energy) / 10.0 * float64(60.0/(zero-timeStamp))
		Score = math.Min(Score, float64(energy)/10.0)
		if ran == 1 {
			addScore = int32(math.Ceil(Score))
		} else {
			addScore = int32(math.Floor(Score))
		}

	} else {
		addScore = 0
	}

	return addScore
}

func (p *NewChampshipsManager) GetAIAddRate(GroupActive int) float64 {
	var rate float64 = 1
	if GroupActive == 1 {
		if G_GameLogicPtr.MLimiteEventManager.GetIsHighRollerPersion() {
			rate = 1.5
		} else {
			rate = 1.0
		}
	}
	if GroupActive == 2 {
		if G_GameLogicPtr.MLimiteEventManager.GetIsHighRollerPersion() {
			rate = 6
		} else {
			rate = 4.5
		}
	}
	if GroupActive == 3 {
		if G_GameLogicPtr.MLimiteEventManager.GetIsHighRollerPersion() {
			rate = 12
		} else {
			rate = 10
		}
	}
	if GroupActive == 4 {
		if G_GameLogicPtr.MLimiteEventManager.GetIsHighRollerPersion() {
			rate = 25
		} else {
			rate = 20
		}
	}
	if GroupActive == 5 {
		if G_GameLogicPtr.MLimiteEventManager.GetIsHighRollerPersion() {
			rate = 42
		} else {
			rate = 36
		}
	}
	if GroupActive == 6 {
		if G_GameLogicPtr.MLimiteEventManager.GetIsHighRollerPersion() {
			rate = 70
		} else {
			rate = 60
		}
	}
	if GroupActive == 7 {
		if G_GameLogicPtr.MLimiteEventManager.GetIsHighRollerPersion() {
			rate = 100
		} else {
			rate = 87
		}
	}
	if GroupActive == 8 {
		if G_GameLogicPtr.MLimiteEventManager.GetIsHighRollerPersion() {
			rate = 120
		} else {
			rate = 113
		}
	}
	if GroupActive == 9 {
		if G_GameLogicPtr.MLimiteEventManager.GetIsHighRollerPersion() {
			rate = 160
		} else {
			rate = 143
		}
	}
	if GroupActive == 10 {
		if G_GameLogicPtr.MLimiteEventManager.GetIsHighRollerPersion() {
			rate = 200
		} else {
			rate = 180
		}
	}
	return rate
}

func (p *NewChampshipsManager) Grouping(playerinfos []*db.SqlPlayerChampionData, GroupActive int) {
	temp := db.SqlChampionshipsStruct{}
	temp.CurChampshipsId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId
	temp.GroupActive = int32(GroupActive)
	CSPlayerInfo := []*msg.ChampshipsPlayerInfo{}
	strr := []string{}
	for i := 0; i < len(playerinfos); i++ {
		dwUin := playerinfos[i].DwUin

		playerinfo := &msg.ChampshipsPlayerInfo{}
		playerinfo.DwUin = dwUin
		playerinfo.IsGet = 0
		playerinfo.IsPlayer = 1
		playerinfo.Score = playerinfos[i].CurScore
		playerinfo.Times = 1
		playerinfo.AIEnum = 0
		playerinfo.CurChampshipsId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId

		res := strconv.Itoa(int(dwUin)) + "_" + "1" + "_" + strconv.Itoa(int(playerinfo.Score)) + "_" + "0" + "_" + "1" + "_" + strconv.Itoa(int(G_GameLogicPtr.M_SvrGlobal.CurChampshipsId)) + "_0" + "_0" + "_name"
		strr = append(strr, res)

		CSPlayerInfo = append(CSPlayerInfo, playerinfo)
		playerinfos[i].IsEnterRank = 1
	}

	StartRobotUin := 200000
	names := p.RandomGetRobotName(MergeConst.G_Champion_People_Cnt - int(len(playerinfos)))

	var Datamap map[int][]int = make(map[int][]int)
	Datamap[1] = []int{-1, 5, 0, 6, 1, 1, 1, 1, 0, 0, 0}
	Datamap[2] = []int{-1, -1, 0, 6, 1, 1, 1, 1, 0, 0, 0}
	Datamap[3] = []int{-1, -1, -1, 6, 1, 1, 1, 1, 0, 0, 0}
	Datamap[4] = []int{-1, -1, -1, -1, 1, 1, 1, 1, 0, 0, 0}
	Datamap[5] = []int{-1, -1, -1, -1, -1, 1, 1, 1, 0, 0, 0}
	Datamap[6] = []int{-1, -1, -1, -1, -1, -1, 1, 1, 0, 0, 0}
	Datamap[7] = []int{-1, -1, -1, -1, -1, -1, -1, 1, 0, 0, 0}
	Datamap[8] = []int{-1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0}
	Datamap[9] = []int{-1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0}
	Datamap[10] = []int{-1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0}
	Datamap[11] = []int{-1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0}

	GetCalcPlayerCnt := func(key int) (int, int) {
		PlayerList := Datamap[key]
		cnt := 0
		cnt1 := 0
		for i := len(PlayerList) - 1; i >= 0; i-- {
			if PlayerList[i] == -1 {
				cnt++
			} else {
				cnt1 = cnt1 + PlayerList[i]
			}
		}
		return cnt, cnt1
	}

	FliterPlayer := func(key int, PlayerI int, AllCnt int) int {
		srcData := Datamap[key]
		copyData := make([]int, len(srcData))
		copy(copyData, srcData)
		Cnt := 0
		Calc, ns := GetCalcPlayerCnt(key)
		remain := AllCnt - ns
		for i := len(srcData) - 1; i >= 0; i-- {
			if srcData[i] == -1 {
				copyData[i] = remain / Calc
			}
		}
		for i := len(copyData) - 1; i >= 0; i-- {
			if copyData[i] > 0 {
				Cnt = Cnt + copyData[i]
				if Cnt >= PlayerI {
					return i + 1
				}
			}
		}
		return 1
	}

	var erengeMap map[int][]int = make(map[int][]int)
	erengeMap[1] = []int{20, 240}
	erengeMap[2] = []int{241, 580}
	erengeMap[3] = []int{581, 1730}
	erengeMap[4] = []int{1731, 2780}
	erengeMap[5] = []int{2781, 4630}
	erengeMap[6] = []int{4631, 7530}
	erengeMap[7] = []int{7531, 12180}
	erengeMap[8] = []int{12181, 21680}
	erengeMap[9] = []int{21681, 35130}
	erengeMap[10] = []int{35131, 64980}
	erengeMap[11] = []int{64981, 71478}

	CurIndex := 0
	for j := int(len(playerinfos)); j < MergeConst.G_Champion_People_Cnt; j++ {
		StartRobotUin = StartRobotUin + 1
		dwUin := StartRobotUin
		var enum int = 0
		ran := rand.Intn(100) + 1
		if ran <= 25 {
			enum = 1
		} else if ran <= 75 {
			enum = 2
		} else {
			enum = 3
		}
		CurIndex += 1
		EnergeIndex := FliterPlayer(int(GroupActive), CurIndex, MergeConst.G_Champion_People_Cnt-len(playerinfos))
		energy := rand.Intn(erengeMap[EnergeIndex][1]-erengeMap[EnergeIndex][0]) + erengeMap[EnergeIndex][0]

		playerinfo := &msg.ChampshipsPlayerInfo{}
		playerinfo.DwUin = int32(dwUin)
		playerinfo.IsGet = int32(energy)
		playerinfo.IsPlayer = 0
		playerinfo.Score = 0
		playerinfo.Times = int32(time.Now().Unix())
		playerinfo.AIEnum = int32(enum)
		playerinfo.Score = p.InitAIAddScore(int32(enum), int32(energy))

		playerinfo.CurChampshipsId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId
		playerinfo.BaseScore = playerinfo.Score
		playerinfo.Name = names[j-int(len(playerinfos))]
		res := strconv.Itoa(int(dwUin)) + "_" + "0" + "_" + strconv.Itoa(int(playerinfo.Score)) + "_" + strconv.Itoa(int(playerinfo.IsGet)) + "_" + strconv.Itoa(int(playerinfo.Times)) + "_" + strconv.Itoa(int(G_GameLogicPtr.M_SvrGlobal.CurChampshipsId)) + "_" + strconv.Itoa(enum) + "_" + strconv.Itoa(int(playerinfo.BaseScore)) + "_" + names[j-int(len(playerinfos))]
		strr = append(strr, res)

		CSPlayerInfo = append(CSPlayerInfo, playerinfo)
	}

	sort.Slice(CSPlayerInfo, func(i, j int) bool { return CSPlayerInfo[i].Score > CSPlayerInfo[j].Score })
	temp.GroupRankData = strings.Join(strr, ";")
	insertId, _ := db.FormatAllMemInsertDb(&temp, "t_championships_data")

	p.MChampshipsGroupData[int32(insertId)] = &ChampshipsGroupData{}
	p.MChampshipsGroupData[int32(insertId)].MChampshipPlayerScoreList = CSPlayerInfo
	p.MChampshipsGroupData[int32(insertId)].CurChampshipId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId
	p.MChampshipsGroupData[int32(insertId)].GroupId = int32(insertId)
	p.MChampshipsGroupData[int32(insertId)].ActiveGroup = int32(GroupActive)
	for j := 0; j < len(playerinfos); j++ {
		dwUin := playerinfos[j].DwUin
		player, ok := G_GameLogicPtr.M_Players[dwUin]
		if ok {
			p.NotifyNewChampshipRank(player, int32(insertId), playerinfos[j], true)
		} else {
			player = G_GameLogicPtr.FindOfflinePlayer(dwUin)
			if player != nil {
				p.NotifyNewChampshipRank(player, int32(insertId), playerinfos[j], false)
			} else {
				p.NotifyNewChampshipRank(player, int32(insertId), playerinfos[j], false)
			}
		}
	}
	// p.MUpdateNotifyList = append(p.MUpdateNotifyList, int32(insertId))

}

func (p *NewChampshipsManager) NotifyNewChampshipRank(player *Player, insertId int32, rankinfo *db.SqlPlayerChampionData, isNotify bool) {

	rankinfo.LastChampGroupID = rankinfo.ChampshipsGroupID
	rankinfo.ChampshipsGroupID = insertId

	if isNotify {
		notify := &msg.NotifyNewChampshipRank{}
		notify.LastChampGroupID = rankinfo.LastChampGroupID
		notify.ChampshipsGroupID = insertId
		notify.IsEnterRank = 1
		notify.GroupRankDataList = p.MChampshipsGroupData[int32(insertId)].MChampshipPlayerScoreList
		agent := player.GetAgentByPlayer()
		data, _ := proto.Marshal(notify)
		G_getGameLogic().PackResInfo(agent, "NotifyNewChampshipRank", data)
	}

	db.FormatAllMemUpdateDb(rankinfo, "t_Player_championships_data", "dwUin")
}

func (p *NewChampshipsManager) NewPlayerEnterRank(args []interface{}) {

	Group := make(map[int][]*db.SqlPlayerChampionData)

	// for _, v := range p.MWaitToRankList {
	// 	units := strings.Split(v.HistoryData, ";")
	// 	active := 0
	// 	RankRate := 0
	// 	if v.HistoryData != "" {
	// 		var temp float64 = 0.0
	// 		for i := 0; i < len(units); i++ {
	// 			items := strings.Split(units[i], ",")
	// 			s, _ := strconv.Atoi(items[1])
	// 			s1, _ := strconv.Atoi(items[2])

	// 			temp += math.Min(float64(s)/float64(s1), 1.0)
	// 			if i == len(units)-1 {
	// 				r, _ := strconv.Atoi(items[0])
	// 				RankRate = r
	// 			}
	// 		}

	// 		a1 := temp / float64(len(units))
	// 		if a1 <= 0.01 {
	// 			active = 1
	// 		} else if a1 <= 0.035 {
	// 			active = 2
	// 		} else if a1 <= 0.07 {
	// 			active = 3
	// 		} else if a1 <= 0.135 {
	// 			active = 4
	// 		} else if a1 <= 0.23 {
	// 			active = 5
	// 		} else if a1 <= 0.37 {
	// 			active = 6
	// 		} else if a1 <= 0.5 {
	// 			active = 7
	// 		} else if a1 <= 0.63 {
	// 			active = 8
	// 		} else if a1 <= 0.8 {
	// 			active = 9
	// 		} else {
	// 			active = 10
	// 		}
	// 		b1 := float64(RankRate) / float64(MergeConst.G_Champion_People_Cnt)
	// 		if b1 <= 0.02 {
	// 			active = active + 2
	// 		} else if a1 <= 0.06 {
	// 			active = active + 1
	// 		} else if a1 <= 0.2 {
	// 			active = active + 0
	// 		} else if a1 <= 0.5 {
	// 			active = active - 1
	// 		} else {
	// 			active = active - 2
	// 		}
	// 		active = int(math.Min(float64(active), 10))
	// 		active = int(math.Max(float64(active), 1))
	// 	} else {
	// 		active = 1
	// 	}
	// 	_, ok := Group[active]
	// 	if ok {
	// 		Group[active] = append(Group[active], v)
	// 	} else {
	// 		Group[active] = []*db.SqlPlayerChampionData{}
	// 		Group[active] = append(Group[active], v)
	// 	}
	// }

	// ScoreGroup
	for _, v := range p.MWaitToRankList {
		units := strings.Split(v.HistoryData, ";")
		active := 0
		if v.HistoryData != "" {
			var LastScore int = 0
			items := strings.Split(units[len(units)-1], ",")
			s, _ := strconv.Atoi(items[1])
			LastScore = s
			active = p.ScoreGroup(int32(LastScore), v.MaxHistoryScore)
		} else {
			active = 1
		}
		_, ok := Group[active]
		if ok {
			Group[active] = append(Group[active], v)
		} else {
			Group[active] = []*db.SqlPlayerChampionData{}
			Group[active] = append(Group[active], v)
		}
	}

	activeIds := []int{}
	for k, _ := range Group {
		activeIds = append(activeIds, k)
	}
	sort.Slice(activeIds, func(i, j int) bool {
		return activeIds[i] < activeIds[j]
	})

	unitPlayerCnt := int(math.Ceil(float64(MergeConst.G_Champion_People_Cnt) * 0.33))

	for i := 0; i < len(activeIds); i++ {
		temp := Group[activeIds[i]]
		mod := len(temp) % unitPlayerCnt
		allG := len(temp) / unitPlayerCnt

		if allG == 0 {
			if i < len(activeIds)-1 {
				Group[activeIds[i+1]] = append(Group[activeIds[i+1]], temp...)
			} else {
				if len(temp) > 0 {
					p.Grouping(temp, activeIds[i])
				}
			}
		} else {
			for m := 0; m < allG; m++ {
				grouping := temp[unitPlayerCnt*m : unitPlayerCnt*(m+1)]
				if mod > 0 {
					if mod <= 5 {
						cnt := mod / allG
						remain := mod % allG
						if m < remain {
							grouping = append(grouping, temp[allG*unitPlayerCnt+m*(cnt+1):allG*unitPlayerCnt+m*(cnt+1)+cnt+1]...)
						} else {
							grouping = append(grouping, temp[allG*unitPlayerCnt+remain*(cnt+1)+(m-remain)*cnt:allG*unitPlayerCnt+remain*(cnt+1)+(m-remain)*cnt+cnt]...)
						}
					}
				}

				p.Grouping(grouping, activeIds[i])
			}
			if mod > 5 {
				grouping := temp[unitPlayerCnt*allG:]
				p.Grouping(grouping, activeIds[i])
			}
		}

	}

	p.MWaitToRankList = make(map[int32]*db.SqlPlayerChampionData)
}

func (p *NewChampshipsManager) OpenNewChampShip(args []interface{}) {

	G_GameLogicPtr.M_SvrGlobal.CurChampshipsId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId + 1
	G_GameLogicPtr.M_SvrGlobal.StartChampshipsSvrTime = args[0].(int32)
	G_GameLogicPtr.M_SvrGlobal.WaitToRank = ""
	G_GameLogicPtr.M_SvrGlobal.InsertChampshipsSvrTime = 0
	p.MUpdateNotifyList = []int32{}
	p.MWaitToRankList = make(map[int32]*db.SqlPlayerChampionData)
	p.MStatus = 1
	p.IsLoadDB = true

	notify := &msg.NotifyChampshipOpen{}
	notify.CurChampshipsId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId
	data, _ := proto.Marshal(notify)
	G_getGameLogic().broadcastInfoAllPlayer("NotifyChampshipOpen", data)

	db.FormatAllMemUpdateDb(&G_GameLogicPtr.M_SvrGlobal, "t_server_global_data", "Id")

}

func (p *NewChampshipsManager) OpenChampShipTimes(args []interface{}) {
	p.MStatus = 2
	notify := &msg.NotifyChampshipTimesOpen{}
	notify.CurChampshipsId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId
	data, _ := proto.Marshal(notify)
	G_GameLogicPtr.broadcastInfoAllPlayer("NotifyChampshipTimesOpen", data)
}

func (p *NewChampshipsManager) CloseChampShipTimes(args []interface{}) {
	p.MStatus = 1
	notify := &msg.NotifyChampshipTimesClose{}
	notify.CurChampshipsId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId
	data, _ := proto.Marshal(notify)
	G_GameLogicPtr.broadcastInfoAllPlayer("NotifyChampshipTimesClose", data)
}

func (p *NewChampshipsManager) Notify_Clock_Tick_Sec(args []interface{}) {
	timeStamp := args[0].(int64)
	t := time.Unix(timeStamp, 0).Local()
	zero := timeStamp - (int64)(t.Hour()*3600+t.Minute()*60+t.Second())
	OpenTime := zero + MergeConst.G_Champion_Start_Offset
	OpenTimesTime := zero + MergeConst.G_Champion_Start_Effect_Time
	CloseTimesTime := zero + MergeConst.G_Champion_Start_Effect_Time + MergeConst.G_Champion_Start_Effect_Durtion
	DeleteLastTimesTime := zero + MergeConst.G_Champion_settlement_Duration
	if G_GameLogicPtr.M_SvrGlobal.StartChampshipsSvrTime < int32(OpenTime) { //今日没有开启
		if timeStamp >= OpenTime { //开启
			GoUtil.CallEvent(MergeConst.Notify_Champion_Renew, []interface{}{int32(OpenTime)})
		} else {
			//开启时间未到
			if p.MStatus == 1 {
				GoUtil.CallEvent(MergeConst.Notify_EndChampShip, []interface{}{int32(OpenTime)})
			}

		}
	} else {
		if p.MStatus == 0 {
			p.MStatus = 1
		}

		if !p.IsLoadDB {
			p.LoadDbDataByGroupId(G_GameLogicPtr.M_SvrGlobal.CurChampshipsId)
			if G_GameLogicPtr.M_SvrGlobal.LastChampshipsId > 0 {
				p.LoadDbDataByGroupId(G_GameLogicPtr.M_SvrGlobal.LastChampshipsId)
			}
			p.IsLoadDB = true
		}
	}

	if p.MStatus == 1 {
		if timeStamp >= OpenTimesTime && timeStamp <= CloseTimesTime {
			GoUtil.CallEvent(MergeConst.Notify_OpenChampShipTimes, []interface{}{int32(OpenTime)})
		}

	}
	if p.MStatus == 2 {
		if timeStamp > CloseTimesTime {
			GoUtil.CallEvent(MergeConst.Notify_CloseChampShipTimes, []interface{}{int32(OpenTime)})
		}
	}
	if p.IsSettle == 0 {
		if timeStamp <= DeleteLastTimesTime {
			p.IsSettle = 1
		} else {
			if G_GameLogicPtr.M_SvrGlobal.LastChampshipsId > 0 {
				p.DeleteOutLineChampship(G_GameLogicPtr.M_SvrGlobal.LastChampshipsId)
				G_GameLogicPtr.M_SvrGlobal.LastChampshipsId = 0
				db.FormatAllMemUpdateDb(&G_GameLogicPtr.M_SvrGlobal, "t_server_global_data", "Id")
			}
		}
	}
	if p.IsSettle == 1 {
		if timeStamp > DeleteLastTimesTime {
			notify := &msg.NotifyChampshipSettleClose{}
			notify.LastChampshipsId = G_GameLogicPtr.M_SvrGlobal.LastChampshipsId
			data, _ := proto.Marshal(notify)
			G_GameLogicPtr.broadcastInfoAllPlayer("NotifyChampshipSettleClose", data)
			p.IsSettle = 0
			if G_GameLogicPtr.M_SvrGlobal.LastChampshipsId > 0 {
				p.DeleteOutLineChampship(G_GameLogicPtr.M_SvrGlobal.LastChampshipsId)
				G_GameLogicPtr.M_SvrGlobal.LastChampshipsId = 0
				db.FormatAllMemUpdateDb(&G_GameLogicPtr.M_SvrGlobal, "t_server_global_data", "Id")
			}

		}
	}
	if p.MStatus == 1 && timeStamp >= OpenTime+1800 && timeStamp >= int64(G_GameLogicPtr.M_SvrGlobal.InsertChampshipsSvrTime)+1800 {
		index := 1
		for {
			CurTime := OpenTime + int64(1800*index)
			NextTime := OpenTime + int64(1800*(index+1))
			if timeStamp >= CurTime && timeStamp < NextTime {
				G_GameLogicPtr.M_SvrGlobal.InsertChampshipsSvrTime = int32(CurTime)
				db.FormatAllMemUpdateDb(&G_GameLogicPtr.M_SvrGlobal, "t_server_global_data", "Id")
				GoUtil.CallEvent(MergeConst.Notify_Champion_Enter_Rank, []interface{}{int32(CurTime)})
				break
			}
			index++
		}
	}

}

func (p *NewChampshipsManager) EndChampShip(args []interface{}) {
	p.MStatus = 0
	G_GameLogicPtr.M_SvrGlobal.LastChampshipsId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId
	db.FormatAllMemUpdateDb(&G_GameLogicPtr.M_SvrGlobal, "t_server_global_data", "Id")

	notify := &msg.NotifyChampshipSettleOpen{}
	notify.LastChampshipsId = G_GameLogicPtr.M_SvrGlobal.LastChampshipsId
	data, _ := proto.Marshal(notify)
	G_GameLogicPtr.broadcastInfoAllPlayer("NotifyChampshipSettleOpen", data)

	notify1 := &msg.NotifyChampshipClose{}
	notify1.CurChampshipsId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId
	data1, _ := proto.Marshal(notify1)
	G_GameLogicPtr.broadcastInfoAllPlayer("NotifyChampshipClose", data1)

	p.NotifyRenewChampshipData()
}

func (p *NewChampshipsManager) NotifyRenewChampshipData() {

	for i := 0; i < len(p.MUpdateNotifyList); i++ {
		groupid := p.MUpdateNotifyList[i]
		GroupData, ok := p.MChampshipsGroupData[groupid]
		if ok {
			playerlist := GroupData.MChampshipPlayerScoreList
			for j := 0; j < len(playerlist); j++ {
				if playerlist[j].IsPlayer == 1 {
					dwUin := playerlist[j].DwUin
					player, ok1 := G_GameLogicPtr.M_Players[dwUin]
					if ok1 {
						agent := player.GetAgentByPlayer()
						notify := &msg.NotifyUpdateChampshipRank{}
						notify.ChampshipsGroupID = groupid
						notify.GroupRankDataList = playerlist
						data, _ := proto.Marshal(notify)
						G_getGameLogic().PackResInfo(agent, "NotifyUpdateChampshipRank", data)
					} else {

					}
				}
			}
		}
	}
	p.MUpdateNotifyList = p.MUpdateNotifyList[0:0]
}

func (p *NewChampshipsManager) ReqChampshipData(player *Player, buf []byte) {
	req := &msg.ReqChampshipData{}
	proto.Unmarshal(buf, req)
	res := &msg.ResChampshipData{}
	_, ok := p.MChampshipsGroupData[req.ChampshipsGroupID]
	if ok {
		res.GroupRankDataList = p.MChampshipsGroupData[req.ChampshipsGroupID].MChampshipPlayerScoreList
	}
	res.ChampshipsGroupID = req.ChampshipsGroupID
	res.Status = p.MStatus
	res.IsSettle = p.IsSettle
	res.EndTime = G_GameLogicPtr.M_SvrGlobal.StartChampshipsSvrTime + MergeConst.G_Champion_Duration
	res.EndSettleTime = G_GameLogicPtr.M_SvrGlobal.StartChampshipsSvrTime - MergeConst.G_Champion_Start_Offset + MergeConst.G_Champion_Start_Effect_Time + MergeConst.G_Champion_Start_Effect_Durtion
	agent := player.GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResChampshipData", data)
}

func (p *NewChampshipsManager) InitManager() {
	GoUtil.RegisterEvent(MergeConst.Notify_Champion_Renew, p.OpenNewChampShip, p)
	GoUtil.RegisterEvent(MergeConst.Notify_Champion_Enter_Rank, p.NewPlayerEnterRank, p)
	GoUtil.RegisterEvent(MergeConst.Notify_OpenChampShipTimes, p.OpenChampShipTimes, p)
	GoUtil.RegisterEvent(MergeConst.Notify_CloseChampShipTimes, p.CloseChampShipTimes, p)
	GoUtil.RegisterEvent(MergeConst.Notify_EndChampShip, p.EndChampShip, p)
	GoUtil.RegisterEvent(MergeConst.Notify_Clock_Tick_Sec, p.Notify_Clock_Tick_Sec, p)
	p.MChampshipMap = make(map[int32]*db.SqlChampionshipsStruct)
	p.MChampshipPlayerMap = make(map[int32][]*msg.ChampshipsPlayerInfo)
	p.MChampshipsGroupData = make(map[int32]*ChampshipsGroupData)

	p.MStatus = 0
	p.IsSettle = 0
	p.IsLoadDB = false
	p.MUpdateNotifyList = []int32{}
	p.MWaitToRankList = make(map[int32]*db.SqlPlayerChampionData)
	p.MAllPlayerRankList = make(map[int32]*db.SqlPlayerChampionData)
	p.McronSave = cron.New()
	p.McronSaveID, _ = p.McronSave.AddFunc("@every 70s", func() {
		if p.MStatus > 0 {
			p.NotifyRenewChampshipData()
		}
	})
	p.RobotCronID, _ = p.McronSave.AddFunc("@every 1m", func() {
		if p.MStatus > 0 {
			p.AIScoreGrowth1m()
		}

	})

	p.RobotCronID5m, _ = p.McronSave.AddFunc("@every 5m", func() {
		// p.ModifyBaseAIScore5m()
	})

	p.RobotCronID10s, _ = p.McronSave.AddFunc("@every 30m", func() {
		if p.MStatus > 0 {
			// p.RobotIntervalAddScore30m()
		}
	})
	p.McronSave.Start()
}

func (p *NewChampshipsManager) GetModifyScoreCnt(RelativeScore int32) int {
	var cnt int = 0
	if float64(RelativeScore)/float64(MergeConst.G_Champion_Max_Score) < 0.02 {
		cnt = 6
	} else if float64(RelativeScore)/float64(MergeConst.G_Champion_Max_Score) < 0.0265 {
		cnt = 5
	} else if float64(RelativeScore)/float64(MergeConst.G_Champion_Max_Score) < 0.0345 {
		cnt = 4
	} else if float64(RelativeScore)/float64(MergeConst.G_Champion_Max_Score) < 0.0542 {
		cnt = 3
	} else if float64(RelativeScore)/float64(MergeConst.G_Champion_Max_Score) < 0.0865 {
		cnt = 2
	} else if float64(RelativeScore)/float64(MergeConst.G_Champion_Max_Score) < 0.194 {
		cnt = 1
	}
	return cnt
}

func (p *NewChampshipsManager) ModifyBaseAIScore5m() {
	needToUpdateDb := []int32{}
	for k, v := range p.MChampshipsGroupData {

		if v.CurChampshipId != G_GameLogicPtr.M_SvrGlobal.CurChampshipsId {
			continue
		}
		sort.Slice(v.MChampshipPlayerScoreList, func(i, j int) bool {
			return v.MChampshipPlayerScoreList[i].Score > v.MChampshipPlayerScoreList[j].Score
		})
		var AddCoreCnt int = 0
		var CurCoreCnt int = 0
		var MaxScore int32 = 0

		for i := 0; i < len(v.MChampshipPlayerScoreList); i++ {
			if v.MChampshipPlayerScoreList[i].IsPlayer == 1 {
				AddCoreCnt = p.GetModifyScoreCnt(v.MChampshipPlayerScoreList[i].Score)
				MaxScore = v.MChampshipPlayerScoreList[i].Score

				break
			}
		}
		isUpdate := false
		if AddCoreCnt > 0 {
			for i := 0; i < len(v.MChampshipPlayerScoreList); i++ {
				if v.MChampshipPlayerScoreList[i].IsPlayer == 0 {
					CurCoreCnt++
					if CurCoreCnt > AddCoreCnt {
						break
					}
					del := v.MChampshipPlayerScoreList[i].Score - v.MChampshipPlayerScoreList[i].BaseScore

					if del >= 0 && v.MChampshipPlayerScoreList[i].Score < MaxScore {
						v.MChampshipPlayerScoreList[i].BaseScore = MaxScore
						v.MChampshipPlayerScoreList[i].Score = MaxScore + del + rand.Int31n(20)
						isUpdate = true
					}
				}
			}
			if isUpdate {
				sort.Slice(v.MChampshipPlayerScoreList, func(i, j int) bool {
					return v.MChampshipPlayerScoreList[i].Score > v.MChampshipPlayerScoreList[j].Score
				})
				p.SaveScoreDataByID(v.MChampshipPlayerScoreList)
				isAdd := false
				for i := 0; i < len(p.MUpdateNotifyList); i++ {
					if p.MUpdateNotifyList[i] == k {
						isAdd = true
						break
					}
				}
				if !isAdd {
					p.MUpdateNotifyList = append(p.MUpdateNotifyList, k)
				}
				needToUpdateDb = append(needToUpdateDb, k)
			}

		}
	}
	for i := 0; i < len(needToUpdateDb); i++ {
		p.SaveDbDataByGroupId(needToUpdateDb[i])
	}
}
func (p *NewChampshipsManager) AIScoreGrowth1m() {
	seed := time.Now().Unix()
	// rand.Seed(seed)
	rand.New(rand.NewSource(seed))
	needToUpdateDb := []int32{}
	timeStamp := time.Now().Unix()
	t := time.Unix(timeStamp, 0).Local()
	zero := timeStamp - (int64)(t.Hour()*3600+t.Minute()*60+t.Second()) + 3600*24
	for k, v := range p.MChampshipsGroupData {
		ishaveRobot := false
		if v.CurChampshipId != G_GameLogicPtr.M_SvrGlobal.CurChampshipsId {
			continue
		}
		for i := 0; i < len(v.MChampshipPlayerScoreList); i++ {
			if v.MChampshipPlayerScoreList[i].IsPlayer == 0 {
				var addScore int32 = 0
				if v.MChampshipPlayerScoreList[i].AIEnum == 1 {
					ishaveRobot = true
					energy := v.MChampshipPlayerScoreList[i].IsGet
					openTime := v.MChampshipPlayerScoreList[i].Times
					rate := float64(int32(timeStamp)-openTime) / 1800
					rate = math.Min(rate, 1)
					Score := float64(energy) / 10.0 * float64(rate)
					addScore = int32(math.Floor(Score))
				}
				if v.MChampshipPlayerScoreList[i].AIEnum == 2 {
					ishaveRobot = true
					energy := v.MChampshipPlayerScoreList[i].IsGet
					openTime := v.MChampshipPlayerScoreList[i].Times
					// rate := float64(int32(timeStamp)-openTime) / float64(int32(zero)-openTime)
					var Score float64 = 0
					if int32(timeStamp)-openTime <= 3600 {
						rate := float64(int32(timeStamp)-openTime) / 3600
						Score = float64(energy) / 10.0 * 0.667 * float64(rate)
					} else {
						rate := float64(int32(timeStamp)-openTime-3600) / float64(int32(zero)-3600-openTime)
						Score = float64(energy)/10.0*0.333*float64(rate) + float64(energy)/10.0*0.667
					}

					addScore = int32(math.Floor(Score))
				}

				if v.MChampshipPlayerScoreList[i].AIEnum == 3 {
					ishaveRobot = true
					energy := v.MChampshipPlayerScoreList[i].IsGet
					openTime := v.MChampshipPlayerScoreList[i].Times
					rate := float64(int32(timeStamp)-openTime) / float64(int32(zero)-openTime)
					Score := float64(energy) / 10.0 * float64(rate)
					addScore = int32(math.Floor(Score))
				}
				temp := v.MChampshipPlayerScoreList[i].BaseScore + addScore
				v.MChampshipPlayerScoreList[i].Score = int32(math.Max(float64(temp), float64(v.MChampshipPlayerScoreList[i].Score)))
			}
		}
		if ishaveRobot {
			sort.Slice(v.MChampshipPlayerScoreList, func(i, j int) bool {
				return v.MChampshipPlayerScoreList[i].Score > v.MChampshipPlayerScoreList[j].Score
			})
			p.SaveScoreDataByID(v.MChampshipPlayerScoreList)
			isAdd := false
			for i := 0; i < len(p.MUpdateNotifyList); i++ {
				if p.MUpdateNotifyList[i] == k {
					isAdd = true
					break
				}
			}
			if !isAdd {
				p.MUpdateNotifyList = append(p.MUpdateNotifyList, k)
			}
			needToUpdateDb = append(needToUpdateDb, k)

		}

	}
	for i := 0; i < len(needToUpdateDb); i++ {
		p.SaveDbDataByGroupId(needToUpdateDb[i])
	}
}

func (p *NewChampshipsManager) RobotIntervalAddScore30m() {
	seed := time.Now().Unix()
	rand.New(rand.NewSource(seed))
	timeStamp := time.Now().Unix()
	t := time.Unix(timeStamp, 0).Local()
	zero := timeStamp - (int64)(t.Hour()*3600+t.Minute()*60+t.Second()) + 3600*24

	needToUpdateDb := []int32{}
	for k, v := range p.MChampshipsGroupData {
		ishaveRobot := false
		if v.CurChampshipId != G_GameLogicPtr.M_SvrGlobal.CurChampshipsId {
			continue
		}
		for i := 0; i < len(v.MChampshipPlayerScoreList); i++ {
			if v.MChampshipPlayerScoreList[i].IsPlayer == 0 {
				var addScore int32 = 0
				if v.MChampshipPlayerScoreList[i].AIEnum == 3 {
					ishaveRobot = true
					energy := v.MChampshipPlayerScoreList[i].IsGet
					openTime := v.MChampshipPlayerScoreList[i].Times
					rate := float64(int32(timeStamp)-openTime) / float64(int32(zero)-openTime)
					Score := float64(energy) / 10.0 * float64(rate)
					addScore = int32(math.Floor(Score))

					v.MChampshipPlayerScoreList[i].Score = v.MChampshipPlayerScoreList[i].BaseScore + addScore
				}
			}
		}
		if ishaveRobot {
			sort.Slice(v.MChampshipPlayerScoreList, func(i, j int) bool {
				return v.MChampshipPlayerScoreList[i].Score > v.MChampshipPlayerScoreList[j].Score
			})
			p.SaveScoreDataByID(v.MChampshipPlayerScoreList)
			isAdd := false
			for i := 0; i < len(p.MUpdateNotifyList); i++ {
				if p.MUpdateNotifyList[i] == k {
					isAdd = true
					break
				}
			}
			if !isAdd {
				p.MUpdateNotifyList = append(p.MUpdateNotifyList, k)
			}
			needToUpdateDb = append(needToUpdateDb, k)

		}

	}
	for i := 0; i < len(needToUpdateDb); i++ {
		p.SaveDbDataByGroupId(needToUpdateDb[i])
	}
}

func (p *NewChampshipsManager) SaveScoreDataByID(playerinfos []*msg.ChampshipsPlayerInfo) {
	for i := 0; i < len(playerinfos); i++ {
		if playerinfos[i].IsPlayer == 1 {

			sql, ok := p.MAllPlayerRankList[playerinfos[i].DwUin]
			if ok {
				sql.CurScore = playerinfos[i].Score
				sql.CurRank = int32(i + 1)
				db.FormatAllMemUpdateDb(sql, "t_Player_championships_data", "dwUin")
			} else {
				sqlStr := "SELECT * FROM t_Player_championships_data WHERE dwUin = ?"
				rankInfo := &db.SqlPlayerChampionData{}
				rankInfo.DwUin = playerinfos[i].DwUin
				if err := db.SqlDb.Get(rankInfo, sqlStr, playerinfos[i].DwUin); err != nil {
					rankInfo.CurScore = playerinfos[i].Score
					rankInfo.CurRank = int32(i + 1)
					db.FormatAllMemInsertDb(rankInfo, "t_Player_championships_data")
				} else {
					rankInfo.CurScore = playerinfos[i].Score
					rankInfo.CurRank = int32(i + 1)
					db.FormatAllMemUpdateDb(rankInfo, "t_Player_championships_data", "dwUin")
				}
			}

		}
	}
}

func (p *NewChampshipsManager) SaveDbDataByGroupId(GroupId int32) {
	_, ok := p.MChampshipsGroupData[GroupId]
	if ok {
		List := p.MChampshipsGroupData[GroupId].MChampshipPlayerScoreList
		strr := []string{}
		for i := 0; i < len(List); i++ {
			Item := List[i]
			unit := strconv.Itoa(int(Item.DwUin)) + "_" + strconv.Itoa(int(Item.IsPlayer)) + "_" + strconv.Itoa(int(Item.Score)) + "_" + strconv.Itoa(int(Item.IsGet)) + "_" + strconv.Itoa(int(Item.Times)) + "_" + strconv.Itoa(int(Item.CurChampshipsId)) + "_" + strconv.Itoa(int(Item.AIEnum)) + "_" + strconv.Itoa(int(Item.BaseScore)) + "_" + Item.Name
			strr = append(strr, unit)
		}
		data := strings.Join(strr, ";")
		sqlStruct := &db.SqlChampionshipsStruct{}
		sqlStruct.ChampshipsGroupID = GroupId
		sqlStruct.GroupRankData = data
		sqlStruct.CurChampshipsId = List[0].CurChampshipsId
		db.FormatAllMemUpdateDb(sqlStruct, "t_championships_data", "ChampshipsGroupID")
	}
}

func (p *NewChampshipsManager) LoadDbDataByGroupId(ChampshipsId int32) {

	sqlStr := "SELECT * FROM t_championships_data WHERE CurChampshipsId = ?"

	sqlStruck := []db.SqlChampionshipsStruct{}

	if err := db.SqlDb.Select(&sqlStruck, sqlStr, ChampshipsId); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)

	} else {
		for m := 0; m < len(sqlStruck); m++ {
			units := strings.Split(sqlStruck[m].GroupRankData, ";")
			list := []*msg.ChampshipsPlayerInfo{}
			for i := 0; i < len(units); i++ {
				item := units[i]
				strr := strings.Split(item, "_")
				temp := &msg.ChampshipsPlayerInfo{}
				dwuin, _ := strconv.Atoi(strr[0])
				temp.DwUin = int32(dwuin)
				IsPlayer, _ := strconv.Atoi(strr[1])
				temp.IsPlayer = int32(IsPlayer)
				Score, _ := strconv.Atoi(strr[2])
				temp.Score = int32(Score)
				IsGet, _ := strconv.Atoi(strr[3])
				temp.IsGet = int32(IsGet)
				Times, _ := strconv.Atoi(strr[4])
				temp.Times = int32(Times)
				CS, _ := strconv.Atoi(strr[5])
				temp.CurChampshipsId = int32(CS)
				AI, _ := strconv.Atoi(strr[6])
				temp.AIEnum = int32(AI)
				BaseScore, _ := strconv.Atoi(strr[7])
				temp.BaseScore = int32(BaseScore)
				temp.Name = ""
				if len(strr) > 8 {
					Name := strr[8]
					temp.Name = Name
				}
				list = append(list, temp)
			}
			termp := &ChampshipsGroupData{}
			termp.CurChampshipId = ChampshipsId
			termp.MChampshipPlayerScoreList = list
			termp.GroupId = sqlStruck[m].ChampshipsGroupID
			termp.ActiveGroup = sqlStruck[m].GroupActive
			p.MChampshipsGroupData[sqlStruck[m].ChampshipsGroupID] = termp

		}
	}

}

func (p *NewChampshipsManager) RandomGetRobotName(cnt int) []string {

	recordCnt := gamedata.GetConfigByName("RandomNameDataBase").NumRecord()
	cnts := G_GameLogicPtr.DisorderLuaTable(recordCnt, cnt)
	names := []string{}
	for i := 0; i < len(cnts); i++ {
		record := gamedata.GetConfigByName("RandomNameDataBase").Record(cnts[i]).(*gamedata.RandomNameDataBase)
		names = append(names, record.EnName)
	}
	return names
}

func (p *NewChampshipsManager) ReqChampshipAddScore(player *Player, buf []byte) {
	req := &msg.ReqChampshipAddScore{}
	proto.Unmarshal(buf, req)
	res := &msg.ResChampshipAddScore{}

	if p.MStatus == 0 {
		res.ResultCode = MergeConst.Protocol_Champship_End
	} else {
		isRank := p.EnterWaitRankList(player.M_DwUin, req.AddScore)
		res.CurScore = p.MAllPlayerRankList[player.M_DwUin].CurScore
		if isRank {
			_, ok := p.MChampshipsGroupData[req.GroupId]
			if ok {
				List := p.MChampshipsGroupData[req.GroupId].MChampshipPlayerScoreList
				isHave := false
				for i := 0; i < len(List); i++ {
					if List[i].DwUin == player.M_DwUin {
						List[i].Score = List[i].Score + req.AddScore
						res.ResultCode = 0
						isHave = true

						break
					}
				}
				sort.Slice(List, func(i, j int) bool { return List[i].Score > List[j].Score })
				p.SaveScoreDataByID(List)
				if !isHave {
					res.ResultCode = MergeConst.Protocol_Champship_No_Join
				} else {
					res.GroupRankDataList = List
					isAdd := false
					for i := 0; i < len(p.MUpdateNotifyList); i++ {
						if p.MUpdateNotifyList[i] == req.GroupId {
							isAdd = true
							break
						}
					}
					if !isAdd {
						p.MUpdateNotifyList = append(p.MUpdateNotifyList, req.GroupId)
					}

					p.SaveDbDataByGroupId(req.GroupId)
				}
			} else {
				res.ResultCode = MergeConst.Protocol_Champship_No_Exsit
			}
		} else {

		}

	}

	res.GroupId = req.GroupId
	agent := player.GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResChampshipAddScore", data)
}

func (p *NewChampshipsManager) ReqChampshipAddTime(player *Player, buf []byte) {
	req := &msg.ReqChampshipAddTime{}
	proto.Unmarshal(buf, req)
	res := &msg.ResChampshipAddTime{}
	if p.MStatus == 0 {
		res.ResultCode = MergeConst.Protocol_Champship_End
	} else {
		_, ok := p.MChampshipsGroupData[req.GroupId]
		if ok {
			List := p.MChampshipsGroupData[req.GroupId].MChampshipPlayerScoreList
			isHave := false
			for i := 0; i < len(List); i++ {
				if List[i].DwUin == player.M_DwUin {
					List[i].Times = List[i].Times + req.AddTimes
					res.ResultCode = 0
					isHave = true
					break
				}
			}
			sort.Slice(List, func(i, j int) bool { return List[i].Score > List[j].Score })
			p.SaveScoreDataByID(List)
			if !isHave {
				res.ResultCode = MergeConst.Protocol_Champship_No_Join
			} else {
				res.GroupRankDataList = List
				p.SaveDbDataByGroupId(req.GroupId)
			}
		} else {
			res.ResultCode = MergeConst.Protocol_Champship_No_Exsit
		}
	}
	res.GroupId = req.GroupId

	agent := player.GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResChampshipAddTime", data)
}

func (p *NewChampshipsManager) ReqChampshipReward(player *Player, buf []byte) {
	req := &msg.ReqChampshipReward{}
	proto.Unmarshal(buf, req)
	res := &msg.ResChampshipReward{}

	res.ResultCode = 0
	_, ok := p.MChampshipsGroupData[req.GroupId]
	if ok {
		List := p.MChampshipsGroupData[req.GroupId].MChampshipPlayerScoreList
		sort.Slice(List, func(i, j int) bool { return List[i].Score > List[j].Score })
		// p.SaveScoreDataByID(List)
		for i := 0; i < len(List); i++ {
			if List[i].DwUin == player.M_DwUin {
				if List[i].IsGet == 0 {
					List[i].IsGet = 1
					p.SaveDbDataByGroupId(req.GroupId)
				} else {
					res.ResultCode = MergeConst.Protocol_Champship_Have_GetWarded
				}

				break
			}
		}
	} else {
		res.ResultCode = MergeConst.Protocol_Champship_No_Exsit
	}

	agent := player.GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResChampshipReward", data)
}
